package com.clsfd;

import java.util.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.log4j.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

//Import classified classes
import com.clsfd.database.DatabaseConnection;
import com.clsfd.database.Subscription;
import com.clsfd.database.VehicleAlert;
import com.clsfd.database.LandAlert;
import com.clsfd.sms.SMSHandler;
import com.clsfd.charging.*;
import com.clsfd.database.SystemParams;
import com.clsfd.sms.SMSHandler;
import com.logging.DcLogFormatter;

public class Autorenew {

		public static void main (String args[]) throws Exception{
			// Initialize the objects and variables
			DatabaseConnection sql= new DatabaseConnection(null);			
			ChargeCustomer charge = new ChargeCustomer(sql);
			SystemParams sysparam = new SystemParams(sql);
			SMSHandler smscon = new SMSHandler(sysparam);
			Calendar cal = Calendar.getInstance(); 
			Date today = new Date();
			//Loging intialization
			Logger Log=null;
			FileHandler filehandler = new FileHandler(sysparam.getSmsHandlerLogFile()+"%g.log",1000000000,3,true);
			Formatter formatterTxt=new DcLogFormatter();
			filehandler.setFormatter(formatterTxt);
			Log = Logger.getLogger("SmsHandler");
			Log.addHandler(filehandler);
			Log.setLevel(Level.parse(sysparam.getSmsHandlerLogLevel()));				
			Log.setLevel(Level.INFO);	
			
			Log.info("Autorenew: Starting Autorenew job");
			// Get Expiring customers from DB			
			Collection<Subscription> subscribercollection=sql.getExpiringSubscriptions(100);	
			Iterator<Subscription> expiredsub =subscribercollection.iterator();
			// Selecting one customer at a time
			while(expiredsub.hasNext()){
				Subscription expsub=expiredsub.next();
				String msisdn= expsub.getMsisdn();
				String lang = expsub.getLanguage();
				String message = null;
				Date expdate = expsub.getExpiretedate();
				//ChargeEvent CE = null;
				String desc = sysparam.getParameter("chargedesc");
				ChargeStatus stat=charge.Charge(msisdn, ChargeEvent.SUSCRIBE, desc);
				  Log.info("Autorenew: Charging executed to ="+ msisdn);
				  //Check the charge is success
				if(stat.equals(ChargeStatus.SUCCESS)){
					String dateincrease = sysparam.getParameter("Renewperiod");
								
						
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
					cal.add(Calendar.DATE,Integer.parseInt(dateincrease));
					System.out.println(cal.getTime());
					String datenew = dateFormat.format(cal.getTime());			
					//System.out.println("test"+dateFormat.format(today));
					expsub.setExpiretedate(datenew);
					Log.info("Autorenew: Charging success to ="+ msisdn);
					//send message to customers  based on language
					if(expsub.getLanguage().equals("si")){
					message = " Classified sevava sadaha liyapadinchiya " + datenew + " dina dakwa aluth kara atha. Ea sadaha Rs 50 + tax aya karagannai";	
					smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), message);
					} else if (expsub.getLanguage().equals("ta")){
						message = " Tamil message ";
						smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), message);	
					} else {
						message = " Your Subscription for the classified service is extended to" + datenew + " and charged Rs 50 + tax for the service.";
						smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), message);
					}
					
					  //Check the charge is insufficient
				}   else if (stat.equals(ChargeStatus.INSUFFICIENTBAL)){
					//check the user has to purge
					int validity = Integer.parseInt(sysparam.getParameter("Subscriptionvalidity"));
					DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					//Date newexpirydate = (Date)format.parse(newexpiry);
					Date expiredate =  new Date();
					expiredate = expsub.getExpiretedate();
					cal.setTime(expiredate);
					cal.add(Calendar.DATE,validity);
					String newexpiredate = format.format(cal.getTime());
					System.out.println(newexpiredate);
					if (newexpiredate.compareTo(format.format(today))< 0 ){
						// delete the sub
						expsub.deleteSubscription();
					
						Log.info("Autorenew: Customer purge ="+ msisdn);
						//send message
						if(expsub.getLanguage().equals("si")){
						smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("purge_msg_sin"));
						} else if (expsub.getLanguage().equals("ta")){
							smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("purge_msg_tam"));	
						} else {
							smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("purge_msg_eng"));
						}
					
					
					}
					 
					else {
						
						// log whether charging has failed
						
						Log.info("Autorenew: Charging failed to ="+ msisdn);
						//send message
						if(expsub.getLanguage().equals("si")){
						smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("chargefailed_msg_sin"));
						} else if (expsub.getLanguage().equals("ta")){
							smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("chargefailed_msg_tam"));	
						} else {
							smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("chargefailed_msg_eng"));
						}
						
					}
					
					
					
				}else {
			// log whether charging has failed
				
					Log.info("Autorenew: Charging failed to ="+ msisdn);
					//send message
					if(expsub.getLanguage().equals("si")){
					smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("chargefailed_msg_sin"));
					} else if (expsub.getLanguage().equals("ta")){
						smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("chargefailed_msg_tam"));	
					} else {
						smscon.SendTextMessage(msisdn, sysparam.getOriginationAddress(), sysparam.getParameter("chargefailed_msg_eng"));
					}
				}
			
				
		}
			Log.info("Charging process completed");	
			
		}
}
